package MyAdmin.Filter;

import MyFramePro.Domain.Entity.LoginUser;
import MyFramePro.Domain.ResponseResult;
import MyFramePro.Enums.AppHttpCodeEnum;
import MyFramePro.Utils.JwtUtil;
import MyFramePro.Utils.RedisCache;
import MyFramePro.Utils.WebUtils;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 这里是 ”后台管理“ 认证的过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        //1.获取前端传来的 token 请求头
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){    //针对不需要 token 的请求，则直接放行
            chain.doFilter(request,response);
            return;
        }

        //2.解析获取 userId
        Claims claims = null;
        ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN); //这里为异常信息
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {     //token 不存在或者非法时，给出提示
//            e.printStackTrace();
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        String userId = claims.getSubject();    //这里将传入的 token 进行解析，获取到 userId

        //3.从 redis 中获取用户信息 value
        LoginUser loginUser = redisCache.getCacheObject("behind-login:" + userId);
        if(Objects.isNull(loginUser)){
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }

        //4.存入 SecurityContextHolder
        //TODO 获取权限信息封装到 Authentication 中
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        chain.doFilter(request,response);
    }

}
